require("core")
require("geometry")
require("collision_utils")
require("effects")
require("sprite")
require("camera")
require("tilemap")
require("screenmanager")
require("sound_manager")
require("dialogs")
require("player_stuff")
require("world_objects")
require("maps")
require("popup_screens")
require("game_screens")
require("object_container")
require("background")
require("player")
require("enemies")

--------------------
-- Global variables
--------------------

-- frame buffer
frame_buffer = love.graphics.newFramebuffer()

-- for fixed update
sleep_time = 0.0
delta_time = 0.0
acculumator = 0.0
update_counter = 0

-- screen manager
screen_manager = nil
sound_manager = nil

-- fonts
normal_font = nil
small_font = nil

--------------------
-- Loading function
--------------------
function love.load()
	-- load fonts
	normal_font = love.graphics.newImageFont("content/fonts/font.png",
	    " abcdefghijklmnopqrstuvwxyz" ..
	    "ABCDEFGHIJKLMNOPQRSTUVWXYZ0" ..
	    "123456789.,!?-+/():;%&`'*#=[]\"")
	small_font = 	love.graphics.newImageFont("content/fonts/font-small.png",
		    " abcdefghijklmnopqrstuvwxyz" ..
		    "ABCDEFGHIJKLMNOPQRSTUVWXYZ0" ..
		    "123456789.,!?-+/():;%&`'*#=[]\"")
	
    -- sound_manager
    sound_manager = SoundManager.new()

    -- screen manager
    screen_manager = ScreenManager.new()
    screen_manager:loadScreen(MainScreen.new())
end

--------------------
-- Fixed Update function
--------------------
function love.update(dt)
    delta_time = love.timer.getDelta()
    acculumator = acculumator + delta_time
    update_counter = math.floor(acculumator / global_delta_time)

    while acculumator > global_delta_time do
        screen_manager:update()
        acculumator = acculumator - global_delta_time
    end
end

--------------------
-- Draw function
--------------------
function love.draw()
	love.graphics.reset()
    -- draw game
	love.graphics.scale(2, 2)
    screen_manager:draw()

	if global_debug then
		love.graphics.setFont(small_font)
		drawString("FPS" .. love.timer.getFPS(), 100, 5)
	end
end

--------------------
-- Keypress function
--------------------
function love.keypressed(key, unicode)
    screen_manager:updateKeyPress(key)
    
    if key == "escape" then
        love.event.push('q')
    end
end

--------------------
-- Keyrelease function
--------------------
function love.keyreleased(key, unicode)
    screen_manager:updateKeyRelease(key)
end

--------------------
-- love quit
--------------------
function love.quit()
	-- clear the image cache
	clearImageCache()
    
    -- clear the sound cache
    clearSoundCache()

	-- delete fonts
	normal_font = nil
	small_font = nil
    
    dprint("System", "Quitting the game.")
end
